﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;
using Coding4Fun.Toolkit.Controls;
using Coding4Fun.Toolkit.Controls.Common;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Reactive;
using Microsoft.Phone.Shell;
using _300Report.Control;
using _300Report.domain;
using _300Report.Global;

namespace _300Report.Pages
{
    public partial class RoleListPage : PhoneApplicationPage
    {
        public static  string NavigateKey = "RoleName";
        public static RoleListPage Instance;
        private string _roleName;
        private RoleList _roleList;
        private int _pageNum = 1;
        private MactchInfo _mactchInfo;
        public RoleListPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            GlobalIndicator.Instance.IsBusy = true;
            _roleName = this.NavigationContext.QueryString[NavigateKey];
            Instance = this;
            GetRoleList(_roleName, _pageNum);
        }


        #region 第一页

        /// <summary>
        /// 获取战斗列表
        /// </summary>
        /// <param name="roleName"></param>
        /// <param name="pageNum"></param>
        private void GetRoleList(string roleName,int pageNum)
        {
                Config.HttpGetStringResult(RequestUrl.GetRoleList(roleName, pageNum))
                    .Select(Config.PareseHeroReport<RoleList>)
                    .ObserveOnDispatcher()
                    .Do(ex => GlobalIndicator.Instance.IsBusy = false)
                    .Subscribe(
                         role => ParseMatchInfo(pageNum, role),
                         ex => this.Dispatcher.BeginInvoke(() =>
                         {
                             GlobalIndicator.Instance.IsBusy = false;
                             Config.Toast("网络错误,稍等一会儿.....", 800);
                         }));
            
          
        }

        private void ParseMatchInfo(int pageNum, RoleList ex)
        {
            if (ex.Result == "OK" && ex.List.Count > 0)
            {
                _roleList = ex;
                _pageNum = pageNum;
                this.RoleNameTextBlock.Text = string.Format("{0} 第{1}/{2} 页", _roleName, pageNum,
                    pages.MainPage.MaxPageNum);
                this.RoleLongListSelector.ItemsSource = _roleList.List;
            }
            else //MessageBox.Show("无法获取指定英雄的战斗列表 ╮(╯﹏╰）╭");
            {
                //_pageNum = Convert.ToInt32(this.RoleNameTextBlock.Text.Split('/')[0].Last());
                //MessageBox.Show("_pageNum =" + _pageNum);
                Config.Toast("无法获取指定英雄的战斗列表 ╮(╯﹏╰）╭", 800);
            }
        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
           
            if (_pageNum<=1)
            {
                Config.Toast("已经是第一页-_-#", 800);
                _pageNum = 1;
                return;
            }
            _pageNum -= 1;
            GlobalIndicator.Instance.IsBusy = true;
            GetRoleList(_roleName, _pageNum);
        }

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (_pageNum>=pages.MainPage.MaxPageNum)
            {
                Config.Toast("已经是最后一页-_-#", 800);
                _pageNum = pages.MainPage.MaxPageNum;
                return;
            }
            _pageNum +=1;
            GlobalIndicator.Instance.IsBusy = true;
            GetRoleList(_roleName, _pageNum);
        }

        /// <summary>
        /// 点击查看详情
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RoleLongListSelector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Battel battel = e.AddedItems[0] as Battel;
            //(sender as LongListSelector).SelectedItem = null;
            if (battel != null)
            {
                (sender as LongListSelector).SelectedItem = null;
                this.RoleListPivot.SelectedIndex = 1;
                GlobalIndicator.Instance.IsBusy = true;
                this.MatchInfoControl.Visibility = Visibility.Collapsed;
                try
                {
                    GetMatchInfo(battel.MatchID);
                }
                catch (Exception exception)
                {
                    Config.Toast("网络异常...", 800);
                }
               
            }

            
        }

        #endregion

        #region 第二页

        private void GetMatchInfo(int MatchId)
        {
            _mactchInfo = null;
            Config.HttpGetStringResult(RequestUrl.GetRoleMatch(MatchId))
                .Select(res => Config.PareseHeroReport<MactchInfo>(res))
                .ObserveOnDispatcher().Do(ex => GlobalIndicator.Instance.IsBusy = false)
                .Subscribe(ex =>
                {
                    if (ex.Result == "OK")
                    {
                        _mactchInfo = ex;
                        Debug.WriteLine(ex.Match.WinSide[0].Hero.Name);
                        this.MatchInfoControl.Visibility = Visibility.Visible;
                        this.PivotItem2.DataContext = ex.Match;
                        _mactchInfo.Match.WinSide.ForEach(a =>
                        {
                            a.Info = string.Format("{0}/{1}/{2}", a.KillUnitCount, a.TowerDestroy, a.TotalMoney);
                        });
                        _mactchInfo.Match.LoseSide.ForEach(a =>
                        {
                            a.Info = string.Format("{0}/{1}/{2}", a.KillUnitCount, a.TowerDestroy, a.TotalMoney);
                        });
                        this.MatchInfoControl.WinSide.ItemsSource = _mactchInfo.Match.WinSide;
                        this.MatchInfoControl.ListBoxLoseSide.ItemsSource = _mactchInfo.Match.LoseSide;

                    }
                    else
                        Config.Toast(ex.Result, 800);


                }, ex => this.Dispatcher.BeginInvoke(() =>
                         {
                             GlobalIndicator.Instance.IsBusy = false;
                             Config.Toast("网络错误,稍等一会儿.....", 800);
                         })
                );


            

        }



      
        #endregion

        #region 其他

        #region 页面appplicationBar

        private void RoleListPivot_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (this.RoleListPivot.SelectedIndex )
            {
                case 0:
                    this.ApplicationBar = this.Resources["ApplicationBar1"] as ApplicationBar;
                    break;
                case 1:
                    this.MatchInfoControl.Visibility = Visibility.Visible;
                    if (_mactchInfo == null || _mactchInfo.Result != "OK")
                    {
                        this.MatchInfoControl.Visibility = Visibility.Collapsed;
                    }
                   
                    this.ApplicationBar = null;
                    break;
            }
        }

        private void ListBoxLoseSide_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            var v = e.AddedItems;
          if (v!= null &&v.Count>0 &&(v[0] as MactchInfo.RoleInMatch).RoleName!= null)
            {
                NavigationHelper.NavigateExt(this.NavigationService, "/Pages/MainPage.xaml", SearchReportHistoryPage.SearcHistoryKey, (v[0] as MactchInfo.RoleInMatch).RoleName);
            }
         
        }

       

        /// <summary>
        /// 跳页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ApplicationBarMenuItem_OnClick(object sender, EventArgs e)
        {
           InputPrompt inputPrompt = new InputPrompt();
           Background = this.LayoutRoot.Background;
           inputPrompt.Message = string.Format("请输入跳转的页码,当前第{0}/{1}页",_pageNum,pages.MainPage.MaxPageNum);
           inputPrompt.InputScope = new InputScope { Names = { new InputScopeName() { NameValue = InputScopeNameValue.Number } } };
            inputPrompt.Value = _pageNum.ToString("d");
            inputPrompt.Completed += delegate
            {
                if (string.IsNullOrWhiteSpace(inputPrompt.Value))
                {
                    Config.Toast("输入为空-_-#", 500);
                    return;
                }
                int var = -1;
                try
                {
                   var = Convert.ToInt32(inputPrompt.Value);
                    if (var<0)
                    {
                        Config.Toast("输入非法-_-#", 500);
                        return;
                    }
                }
                catch (Exception exception)
                {
                    Config.Toast("输入非法-_-#", 500);
                    return;
                }
                GetRoleList(_roleName, var);
            };
            inputPrompt.Show(); 
        }

       
        #endregion

        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            if (this.RoleListPivot.SelectedIndex == 1)
            {
                this.RoleListPivot.SelectedIndex = 0;
                e.Cancel = true;
                return;
            }
         
        }


        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.MatchInfoControl.WinSide.SelectedItem = null;
            this.MatchInfoControl.ListBoxLoseSide.SelectedItem = null;
            Instance = null;
            GC.Collect();
            base.OnNavigatedFrom(e);
        }

        #endregion


      
    }
}